﻿using System;
using System.Collections.Generic;
using System.Text;

namespace DbfDotNet
{

    public class DbfTable 
    {
        internal Core.DbfFile mDbfFile;

        public DbfTable(string filePath, System.Text.Encoding encoding, DbfVersion version)
        {
            mDbfFile = Core.DbfFile.Get(filePath, encoding, version);
        }

        protected DbfTable()
        {
        }

        public DbfRecord GetRecord(uint rowNo)
        {
            return (DbfRecord)mDbfFile.InternalGetRecord((uint)rowNo, false);
        }

        public int RecordCount
        {
            get { return (int)mDbfFile.RecordCount; }
        }

        public DbfIndex GetIndex(string filepath, SortOrder sortOrder)
        {
            return mDbfFile.GetIndex(filepath, sortOrder);
        }

        public List<Core.ColumnDefinition> Columns
        {
            get { return mDbfFile.Columns; }
        }


    }

    public class DbfTable<TRecord> : DbfTable, 
        IEnumerable<TRecord> where TRecord : DbfRecord, new()
    {
        internal new Core.DbfFile<TRecord> mDbfFile;

        public DbfTable(string filePath, System.Text.Encoding encoding, DbfVersion version)
        {
            mDbfFile = Core.DbfFile<TRecord>.Get(filePath, encoding, version);
            base.mDbfFile = mDbfFile;
        }

        public TRecord NewRecord()
        {
            return mDbfFile.NewRecord();
        }

        #region IEnumerable<TRecord> Members

        public IEnumerator<TRecord> GetEnumerator()
        {
            return mDbfFile.GetEnumerator();
        }

        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }

        #endregion
        
        public new TRecord GetRecord(UInt32 p)
        {
            return (TRecord)mDbfFile.InternalGetRecord((uint)p, false);
        }

        public void Close()
        {
            mDbfFile.StopReading();
            mDbfFile = null;
        }

        public void EmptyTable()
        {
            mDbfFile.EmptyTable();
        }

        public new DbfIndex<TRecord> GetIndex(string filepath, SortOrder sortOrder)
        {
            return (DbfIndex<TRecord>)mDbfFile.GetIndex(filepath, sortOrder);
        }

    }
}
